package com.didi.gulimall.common.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * @author 10626
 */
@Configuration
@EnableConfigurationProperties({RedisProperties.class,RedissonConfigProperties.class})
@ConditionalOnClass(RedissonClient.class)
public class RedissonConfig {
    /**
     * 所有对Redisson的使用都是通过RedissonClient对象
     * @return
     * @throws IOException
     */
    @Bean(destroyMethod="shutdown")
    public RedissonClient redissonClient(RedisProperties redisProperties,RedissonConfigProperties redissonConfigProperties) throws IOException {
        //1、创建配置
        Config config = new Config();
        config.useSingleServer().setAddress("redis://"+redisProperties.getHost()+":"+redisProperties.getPort())
                .setPassword(redisProperties.getPassword())
                .setTimeout(redissonConfigProperties.getTimeout())
                .setRetryAttempts(redissonConfigProperties.getRetryAttempts())
                .setRetryInterval(redissonConfigProperties.getRetryInterval())
                .setConnectionPoolSize(redissonConfigProperties.getConnectionPoolSize())
                .setConnectionMinimumIdleSize(redissonConfigProperties.getConnectionMinimumIdleSize())
                .setPingConnectionInterval(redissonConfigProperties.getPingConnectionInterval());
        //**此项务必设置为redisson解决之前bug的timeout问题关键***** setPingConnectionInterval
        //2、根据Config创建出RedissonClient示例
        return Redisson.create(config);
    }
}
